<?php
/**
 * Created by paperphp
 * User: 22071
 * Date: 2019/9/19
 * Email: <zhendongdong@foxmail.com>
 */

namespace paper\exception;


use paper\App;
use paper\constraint\ExceptionsHandler;

class ExceptionsHandlerRegister
{
    private $app;

    public function __construct(App $app)
    {
        $this->app = $app;
    }

    /**
     * 注册异常处理函数
     */
    public function register()
    {
        //获取用户或者系统的异常处理类
        set_exception_handler($this->appException());
        set_error_handler($this->appError());
    }

    /**
     * @return \Closure
     */
    private function appError()
    {
        return function ($errno, $errstr, $errfile, $errline) {
            $exception = new ErrorException($errno, $errstr, $errfile, $errline);
            //$this->getRenderHandler($exception)->send();
            throw $exception;
        };
    }

    /**
     * @return \Closure
     */
    private function appException()
    {
        return function ($exception) {
            $this->getRenderHandler($exception)->send();
        };
    }

    /**
     * @param $exception
     * @return mixed
     */
    public function getRenderHandler($exception)
    {
        /**@var ExceptionsHandler $exceptionHandler * */
        $exceptionHandler = $this->app->make(ExceptionsHandler::class);
        $exceptionHandler->report($exception);
        return $exceptionHandler->render($exception);
    }
}